# coding=utf-8
# -*- coding: UTF-8 -*-
#
# This file is part of the kernelstudio package.
#
# (c) 2014-2025 zlin <admin@kernelstudio.com>
#
# For the full copyright and license information, please view the LICENSE file
# that was distributed with this source code.
import os.path
from typing import Generator

from ksai.persistence.storage.core import StorageProvider, StorageProviderFactory
from ksai.utils.paths import get_project_storage_path, get_parent_filepath


class LocalStorageProvider(StorageProvider):

    def __init__(self, local_path: str):
        super().__init__()
        self._local_path = local_path

    def save(self, filename: str, data: bytes) -> bool:
        filepath = get_project_storage_path(filename)
        parent_filepath = get_parent_filepath(filepath)
        os.makedirs(parent_filepath, exist_ok=True)

        with open(filepath, 'wb') as f:
            f.write(data)

        return os.path.exists(filepath)

    def stream(self, filename: str, filepath: str) -> Generator:
        pass

    def read(self, filename: str) -> bytes:
        filepath = get_project_storage_path(filename)
        if not os.path.exists(filepath):
            raise FileNotFoundError
        with open(filepath, 'rb') as f:
            return f.read()

    def exists(self, filename):
        filepath = get_project_storage_path(filename)
        return os.path.isfile(filepath)

    def delete(self, filename):
        filepath = get_project_storage_path(filename)
        if os.path.isfile(filepath):
            os.remove(filepath)
            return True
        return False


class LocalStorageProviderFactory(StorageProviderFactory):
    def __init__(self):
        super().__init__()

    def create(self, auto_connect: bool = True) -> StorageProvider:
        local_path = get_project_storage_path()
        os.makedirs(local_path, exist_ok=True)
        return LocalStorageProvider(local_path)
